package com.google.donutrush;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import Services.UserService;
import Services.UserServiceDBimpl;

import com.google.appengine.repackaged.org.json.JSONException;
import com.google.appengine.repackaged.org.json.JSONObject;

public class ConfirmRegFormServlet extends HttpServlet{

	public void doGet(HttpServletRequest request, HttpServletResponse response){
		doPost(request, response);
		
	}
	
	
	
	public void doPost(HttpServletRequest request, HttpServletResponse response){
	
		UserService us = UserServiceDBimpl.getInstance();
		
		//Prepare the json object we create from the request body
		JSONObject jsonObject = null;
		//The object comes in the body as the key in the first element of the ParameterMap (im not sure why)
		//I only converted it to array because I like it better
		Object[] m = request.getParameterMap().keySet().toArray();
		//Create the json from the object in m[0]
		try {
			jsonObject = new JSONObject(m[0].toString());
		} catch (JSONException e1) {
			e1.printStackTrace();
		}
		
		//getting all filled params in the registration form of the json object
		String reqName = "";
		String reqEmail = "";
		
		
		try {
			reqName = (String) jsonObject.get("name");
			reqEmail = (String) jsonObject.get("email");
			
			
		} catch (JSONException e) {
			e.printStackTrace();
		}
		JSONObject newJsonObject=new JSONObject();
		 
		if(us.getUserByEmail(reqEmail)!=null || us.getUserByName(reqName) != null){
			try {
				newJsonObject.put("Error", "bad");
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		else{
			try {
				newJsonObject.put("Error", "none");
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			
		}
		
			
		
		
	response.setContentType("text/plain");
	PrintWriter writer = null;
	try {
		writer = response.getWriter();
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	String myString = newJsonObject.toString();
	writer.println(myString);
	writer.close();

	}
}
